package gold.digger;

import gold.vo.ListNode;
import gold.vo.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC109 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public TreeNode sortedListToBST(ListNode head) {
            List<Integer> valList = new ArrayList<>();
            while (null != head) {
                valList.add(head.val);
                head = head.next;
            }

            return createBSTRecur(valList, 0, valList.size() - 1);
        }

        public TreeNode createBSTRecur(List<Integer> valList, int start, int end) {
            if (start > end || null == valList || null == valList.get(start)) return null;
            int mid = start + (end - start) / 2;
            TreeNode root = new TreeNode(valList.get(mid));
            root.left = createBSTRecur(valList, start, mid - 1);
            root.right = createBSTRecur(valList, mid + 1, end);
            return root;
        }

    }

    public void run() {
        Solution solution = new Solution();
        ListNode head = ListNode.createListFromArrayString("[-10,-3,0,5,9]");
        System.out.println(solution.sortedListToBST(head));
    }

    public static void main(String[] args) throws Exception {
        LC109 an = new LC109();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
